package ssm_zxw.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import ssm_zxw.mapper.RoleMapper;
import ssm_zxw.pojo.Role;
import ssm_zxw.redis.jedisUtils;
import ssm_zxw.service.roleService;

import java.util.List;

@Service("roleService")
public class roleServiceImpl implements roleService {
    @Autowired
    private RoleMapper roleMapper;
    Jedis jedis = jedisUtils.getJedis();
    ObjectMapper mapper = new ObjectMapper();
    @Override
    public List<Role> findAll() {
        String role = jedis.get("role");
        if (role == null || role.length() == 0) {
            List list = roleMapper.findALl();
            try {
                role = mapper.writeValueAsString(list);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            jedis.set("role", role);
            jedis.close();
        }
//        将json转为list集合
        List<Role> list = JSONObject.parseArray(role,Role.class);
       // System.out.println(list);
        return list;
    }
    @Override
    public void addRole(Role role) {
        roleMapper.addRole(role);
        List<Role> list = roleMapper.findALl();
        String s = null;
        try {
            s = mapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        jedis.set("role",s);
    }

    @Override
    public void deleteRole(int id) {
        roleMapper.deleteRole(id);
        List<Role> list = roleMapper.findALl();
        String s = null;
        try {
            s = mapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        jedis.set("role",s);
    }
}
